package com.yugao.fintech.draper.admin.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yugao.fintech.draper.admin.convert.RouteConfConvert;
import com.yugao.fintech.draper.admin.entity.SysRouteConf;
import com.yugao.fintech.draper.admin.mapper.RouteConfMapper;
import com.yugao.fintech.draper.admin.param.FilterDefinitionDTO;
import com.yugao.fintech.draper.auth.dto.RouteConfVO;
import com.yugao.fintech.draper.admin.service.RouteConfigService;
import com.yugao.fintech.draper.admin.param.PredicateDefinitionDTO;
import com.yugao.fintech.draper.auth.mq.RouteMessage;
import com.yugao.fintech.draper.message.queue.client.RedisMQTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.PropertyMapper;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RouteConfigServiceImpl implements RouteConfigService {
    @Autowired
    private RouteConfMapper routeConfMapper;
    @Autowired
    private RedisMQTemplate redisMQTemplate;

    /**
     * 添加路由信息
     */
    @Override
    public Boolean addRouteConf(RouteConfVO routeConfVo) {
        // 保存路由信息
        routeConfMapper.insert(RouteConfConvert.INSTANCE.convert(routeConfVo));
        // 通知mq
        this.sendMq();
        return Boolean.TRUE;
    }

    /**
     * 修改路由信息
     */
    @Override
    public Boolean updateRouteConf(JSONArray routeConf) {
        // 构建路由信息
        List<RouteConfVO> list = routeConf.stream().map(this::convert).collect(Collectors.toList());
        // 删掉所有路由信息
        routeConfMapper.delete(Wrappers.emptyWrapper());
        // 保存路由信息
        for (RouteConfVO routeConfVO : list) {
            routeConfMapper.insert(RouteConfConvert.INSTANCE.convert(routeConfVO));
        }
        // 通知网关加载路由
        this.sendMq();
        return Boolean.TRUE;
    }

    /**
     * 删除路由信息
     */
    @Override
    public Boolean deleteRouteConf(Long id) {
        // 删除路由信息
        routeConfMapper.deleteById(id);
        // 发送消息到mq
        this.sendMq();
        return Boolean.TRUE;
    }

    /**
     * 获取单条路由信息
     */
    @Override
    public RouteConfVO findById(Long id) {
        SysRouteConf routeConf = routeConfMapper.selectById(id);
        return RouteConfConvert.INSTANCE.convert(routeConf);
    }

    /**
     * 查询所有路由信息
     */
    @Override
    public List<RouteConfVO> findAll() {
        List<SysRouteConf> dos = routeConfMapper.selectList(Wrappers.emptyWrapper());
        List<RouteConfVO> dtos = RouteConfConvert.INSTANCE.convert(dos);
        return dtos;
    }

    private void sendMq() {
        redisMQTemplate.send(new RouteMessage(findAll()));
    }

    /**
     * 构建路由信息
     */
    private RouteConfVO convert(Object value) {
        RouteConfVO r = new RouteConfVO();
        Map<String, Object> map = (Map) value;
        PropertyMapper mapper = PropertyMapper.get().alwaysApplyingWhenNonNull();
        mapper.from(map.get(SysRouteConf.Fields.name)).whenNonNull().as(String::valueOf).to(r::setName);
        mapper.from(map.get(SysRouteConf.Fields.routeId)).whenNonNull().as(String::valueOf).to(r::setRouteId);
        mapper.from(map.get(SysRouteConf.Fields.uri))
                .whenNonNull()
                .as(String::valueOf)
                .as(URI::create)
                .as(String::valueOf)
                .to(r::setUri);
        mapper.from(map.get(SysRouteConf.Fields.sortOrder))
                .whenNonNull()
                .as(String::valueOf)
                .as(Integer::parseInt)
                .to(r::setSortOrder);
        mapper.from(map.get(SysRouteConf.Fields.metadata))
                .whenNonNull()
                .as(String::valueOf)
                .as(v -> JSONUtil.toBean(v, Map.class))
                .as(JSONUtil::toJsonStr)
                .to(r::setMetadata);
        mapper.from(map.get(SysRouteConf.Fields.filters))
                .whenNonNull()
                .as(JSONArray::new)
                .as(v -> v.toList(FilterDefinitionDTO.class))
                .as(JSONUtil::toJsonStr)
                .to(r::setFilters);
        mapper.from(map.get(SysRouteConf.Fields.predicates))
                .whenNonNull()
                .as(JSONArray::new)
                .as(v -> v.toList(PredicateDefinitionDTO.class))
                .as(JSONUtil::toJsonStr)
                .to(r::setPredicates);
        return r;
    }
}